<%@page import="com.elookinto.wordlist.MobileDeviceDetector"%>
<%@page contentType="text/html" pageEncoding="UTF-8" import="java.io.*, java.sql.*, javax.sql.*, org.brickred.socialauth.*"%>
<%

    boolean isMobile = isMobile(request, session);
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", -1);

    Cookie cookies[] = request.getCookies();
    Cookie myCookie = null;
    String cookieUid = "uid";

    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            // out.println(cookies[i].getName() + "--- " + cookies[i].getValue() + "<br/>");
            if (cookies[i].getName().equals(cookieUid)) {
                myCookie = cookies[i];
                break;
            }

        }
    }
    String uid = null;
    String loginAccount = null;
    if (session.getAttribute("uid") == null) {
        SocialAuthManager manager = (SocialAuthManager) session.getAttribute("authManager");
        try {
            if (manager != null) {
                java.util.Map<String, String> paramsMap = org.brickred.socialauth.util.SocialAuthUtil.getRequestParametersMap(request);
                AuthProvider provider = manager.connect(paramsMap);
                if (provider != null) {
                    Profile p = provider.getUserProfile();
                    if (p != null && p.getEmail() != null) {
                        uid = p.getEmail();
                    } else {
                        uid = p.getFullName() + p.getDisplayName();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        loginAccount = uid;
    }

    if (uid != null) {
        session.setAttribute("uid", uid);
    } else {
        if (myCookie != null) {
            uid = myCookie.getValue();
            session.setAttribute("uid", uid);
        } else {
            uid = request.getRemoteHost();
            session.setAttribute("uid", uid);
        }
    }
    //out.println("uid=" + uid);
    Cookie cookie = new Cookie("uid", session.getAttribute("uid").toString());
    cookie.setMaxAge(365 * 24 * 60 * 60);
    response.addCookie(cookie);
    String saveListName = request.getParameter("listName");
    String saveWord = request.getParameter("word");
    String gotoTab = request.getParameter("gotoTab");
    if (gotoTab != null) {
        session.setAttribute("gotoTab", gotoTab);
    }

%>
<!DOCTYPE html>
<html>
    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
        <meta name="title" content="Word List" />
        <meta name="description" content=" This word list app is the best tool to help boost your/your family vocabulary. " />
        <meta property="og:title" content="Word List" /> 
        <% if (isMobile) {%>
        <meta name="HandheldFriendly" content="true" />
        <meta name="viewport" content="width=device-width, height=device-height, user-scalable=no" />
        <%}%>
        <meta property="og:description" content="This word list app is the best tool to help boost your/your family vocabulary. " /> 
        <title> Word List </title>


        <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" />
        <link rel="stylesheet" type="text/css" href="css/wordlist.css"/> 
        <link rel="stylesheet" type="text/css" href="css/button.css"/> 
        <link rel="stylesheet" type="text/css" media="screen" href="css/atd.css" />
        <link rel="stylesheet" type="text/css" media="screen" href="js/qtip/jquery.qtip.min.css" />
        <link rel="stylesheet" type="text/css" href="js/jquery.contextMenu.css"/> 
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
        <script type="text/javascript" src="js/jquery.cookie.js"></script>
        <script type="text/javascript" src="js/jquery.limit.js"></script>
        <script src="js/jquery.atd.textarea.js"></script>
        <script src="js/qtip/jquery.qtip.min.js"> </script>
        <script src="js/jquery.contextMenu.js"> </script>
        <script src="js/csshttprequest.js"></script>

        <script type="text/javascript" src="js/wordlist.js"></script>

        <script type="text/javascript">

            var _gaq = _gaq || [];
            _gaq.push(['_setAccount', 'UA-9033082-1']);
            _gaq.push(['_trackPageview']);

            (function() {
                var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
                ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
                var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
            })();

        </script>
        <script type="text/javascript">
            $(document).ready(function() {
                // Match all <A/> links with a title tag and use it as the content (default).
	     
                $('#upload').limit('1000','#charsLeft');
                $('#note').limit('1000','#charsLeft');
                //alert( "cookie" + $.cookie("currentWordList"))
                $.get("retrieve.jsp", {listName: $.cookie("currentWordList"), pub:$.cookie("pub")}, function(data) {
                    // alert(data);
                    $("#wordlist").html(data);
                    $('a.button').qtip();
                });   
                
                $('input:checkbox').click(function() {
                    if($(this).is(":checked")){
                       
                        $.cookie($(this).attr('id'), true,  {   expires: 365});
                    }
                    else {
                        
                        $.cookie($(this).attr('id'), false,  {   expires: 365});  
                    }
                }
            );
               
            <% if (saveListName != null && saveWord != null) {%>
                    var saveListName = "<%= saveListName%>";
                    var saveWord = "<%= saveWord%>";
                    //alert(saveWord);
                    //alert(saveListName);
                    $.post("save.jsp", 
                    {
                        wordList:saveWord, 
                        listName: saveListName }
                    ,
                    function(data2){
                        $.cookie("currentListName", saveListName );
                        retrieveMyList();
                        $("#message").text("Your word '" +saveWord+ "' has been saved to list '"+ saveListName +"'!");

                        var currentWord = saveWord;
                        $.get("retrieve.jsp", {
                            listName: saveListName,
                            currentWord: saveWord
                        }, function(data4) {
                            // alert(data4);
                            // $("#wordlist").html("damnit");
                             
                            $("#wordlist").html(data4);
                            $('#listname').val("");
                            $('#upload').val("");
                             
                        }); 
                    });
                        
                        
            <% } else {%>
                    retrieveMyList();
            <%}%>
                    $("#listname").focus(function() {
                        var $this = $(this);
                        $this.select();
                        // Work around Chrome's little problem
                        $this.mouseup(function() {
                            // Prevent further mouseup intervention
                            $this.unbind("mouseup");
                            return false;
                        });
                    });
                   
           
                    $(document).keyup(function(event) {
                        if ( event.keyCode == 27 ) hideAll();
                    });       

                });
        </script>



    </head>
    <body>
        <div class="wrapper">
            <div id="fb-root"></div>
            <% if (!isMobile) {%>
            <script>(function(d, s, id) {
                var js, fjs = d.getElementsByTagName(s)[0];
                if (d.getElementById(id)) return;
                js = d.createElement(s); js.id = id;
                js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=395273910509570";
                fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'facebook-jssdk'));
            </script>
            <%}%>
            <div>
                <div class="topmenu">   
                    <%@include file="WEB-INF/jspf/menu.jspf" %>
                </div>
                <h2 align="center"> Word Lists  <span style="font-size: small;color:green"> Use the word lists created by experts or <a style="color:graytext" href="javascript:void(0)" onclick="upload(document.getElementById('b'))"> create </a> your own </span>
                </h2>
                <% if (!isMobile) {%>
                <div style="float:right" class="fb-like" data-href="http://www.elookinto.com/wordlist" data-send="true" data-width="450" data-show-faces="true"></div>
                <%}%>
            </div>
            <!--
          <div><object id="test" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" 
                       codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="15" height="15"><PARAM NAME=movie VALUE="http://www.strangecube.com/audioplay/online/audioplay.swf?file=http://onelook.com/pronounce/macmillan/US/word-American-English-pronunciation.mp3&auto=no&sendstop=yes&repeat=1&buttondir=http://www.strangecube.com/audioplay/online/alpha_buttons/negative_small&bgcolor=0xffffff&mode=playpause"><PARAM NAME="allowScriptAccess" value="always" /> <PARAM NAME=quality VALUE=high><PARAM NAME=wmode VALUE=transparent><PARAM NAME=einterface VALUE=yes><embed einterface="yes" allowScriptAccess="always" name="test" 
                                                                                                                                                                                                    src="http://www.strangecube.com/audioplay/online/audioplay.swf?file=http://onelook.com/pronounce/macmillan/US/word-American-English-pronunciation.mp3&auto=no&sendstop=yes&repeat=1&buttondir=http://www.strangecube.com/audioplay/online/alpha_buttons/negative_small&bgcolor=0xffffff&mode=playpause&einterface=yes"
                                                                                                                                                                                                    quality=high wmode=transparent width="15" height="15" align="" TYPE="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed></object></div>
    
            <button onclick="play1('connection')"> test </button>
            -->

            <div style="text-align: center">

                <%
                    for (int i = 0; i <= 6; i++) {
                %>
                <a title="National Reading Vocabulary" style="margin-left:5px;text-decoration: none;font-weight: bold;background: lightgray" href="javascript:void(0)"  onclick="retrieveGradeList(<%=i%>)"> K-<%= i%> </a>
                <% }%>
                <a style="margin-left:5px;text-decoration: none;font-weight: bold;background: lightgray" href="javascript:void(0)"  onclick="retrieveSATList('I')"> SAT </a>
                <a title="SAT Official Guide Words" style="margin-left:5px;text-decoration: none;font-weight: bold;background: lightgray" href="javascript:void(0)"  onclick="retrieveSATList('O')"> SAT II </a>
                <a title="GRE Word List" style="margin-left:5px;text-decoration: none;font-weight: bold;background: lightgray" href="javascript:void(0)"  onclick="retrieveGREList()"> GRE </a>
                <a title="TOEFL Word List" style="margin-left:5px;text-decoration: none;font-weight: bold;background: lightgray" href="javascript:void(0)"  onclick="retrieveTOEFLList()"> TOEFL </a>

            </div>

            <div id="gradeList" style="text-align: center;background-color:lightblue;margin-left: 100px;margin-right: 100px"> </div>

            <div width="100%" id="myWordList" style="text-align: center;background:lavenderblush">

            </div>
            <div style="text-align: center">
                <div style="float:left;margin-right: 20px">  <br/> 
                    <button onclick="choose_dict()"> Choose Dictionaries </button> 
                </div>

                <script type="text/javascript"><!--
                google_ad_client = "ca-pub-1830488441040930";
                /* wordlist */
                google_ad_slot = "4413544198";
                google_ad_width = 728;
                google_ad_height = 90;
                //-->
                </script>
                <script type="text/javascript"
                        src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
                </script><br/>
                <form>
                    <input style="background-color: yellow" type="text" name="word" max="20"/> 
                    <input name="listName" value="Recent" type="hidden" />
                    <input style="font-weight: bold;font-size: large" type="submit"  value="Search Your Word" />
                </form>
                <div style="float:right;margin-right: 20px; text-align: right"> 
                    <%
                        if (uid.equals(request.getRemoteHost())) {%>

                    <b> Login with: </b>
                    <a href="facebook.jsp" title="facebook"><img width="24" height="24" src="http://opensource.brickred.com/socialauthdemo/images/facebook_icon.png" /></a>
                    <a href="yahoo.jsp" title="yahoo"><img width="24" height="24"  src="http://opensource.brickred.com/socialauthdemo/images/yahoomail_icon.jpg" /></a>
                    <a href="twitter.jsp"  title="twitter"><img width="24" height="24" src="http://opensource.brickred.com/socialauthdemo/images/twitter_icon.png" /></a>
                    <a href="google.jsp" title="google"><img width="24" height="24" src="http://socialauth.in/socialauthdemo/images/gmail-icon.jpg" /></a> <br/>
                    <span style="color:chocolate;ont-weight: bold"> To create word lists that can be access from anywhere. </span>
                    <%} else {%>
                    <a href="logout.jsp"> logout </a>
                    <%}%>
                </div>
            </div>
            <div id="inputarea" style="display:none;vertical-align:text-top;width:100%" >
                <table>
                    <tr> <td>
                            Type/Paste Words to the blow box to be saved:<br/> <textarea  id="upload" cols="80" rows="10"> </textarea>
                        </td>

                        <td>
                            Notes:<br/> <textarea  id="note" cols="80" rows="10"> </textarea>
                        </td>
                    </tr>
                </table>


                List Name: <input   size="45" maxlength="65" id="listname" type="text" />
                <img src="images/atdbuttontr.gif"><a href="javascript:check()" id="checkLink">Check Spelling</a>
            </div>

            <button id="b" onclick="upload(this)"> Upload words </button>  <%-- <button onclick="" > Upload Your Recording URL </button>
            <span style="color:red;" id="message" > </span> --%>
            <span style="color:chocolate;font-weight: bold" id="message" > to create/update your own word lists. </span>
            <br/>


            <div id="wordlist" >

            </div>





            <div class="push"> </div>
            <div class='footer' style="width:100%;text-align:center">
                <!--
                <a href="https://chrome.google.com/webstore/detail/demkilcilciablmnmbnnlknjnphcloae"> Install from Chrome Store 2.0 </a> 
                -->

                <span> <b>Please install browser extension for Popup Google Dictionary, </b> </span> 
                <% Browser b = browser(request);
                    if (b != Browser.CHROME) {%>
                (Highlight a word and see definition)
                <a style="font-weight: bold" href="http://crossrider.com/install/16242"> Google Dictionary + Word List </a> <br/>
                <% } else {%>

                <a style="font-weight: bold" href="https://chrome.google.com/webstore/detail/mkjnchpohljkinmppeljneimbbjblcbd"> Google Dictionary + Word List </a> 
                or  <a style="font-weight: bold" href="https://chrome.google.com/webstore/detail/dcmlnfpkppmknmlfmlhihohbdaicpdod"> Word List + Dictionary Lookup </a>
                <br/>
                The <a href="https://chrome.google.com/webstore/detail/demkilcilciablmnmbnnlknjnphcloae">Old One </a> has been outdated.  <br/>

                <% }%>
                <%@include file="footer.jsp" %>
            </div>




            <%-- nodisplayable--%>

            <div id="dialog" title="Choose a dictionary " style="background:yellowgreen;display: none">
                <p style="margin-top:15px"><span class="ui-icon ui-icon-message" style="float:left; margin:0 7px 20px 0;">
                    </span>
                <table> <tr>
                        <td> One Look: </td> <td> <input type="checkbox" id="choose_0" /> </td></tr>
                    <tr>
                        <td>Beginner's Wordsymth: </td> <td><input type="checkbox" id="choose_1" /> </td></tr>
                    <tr>
                        <td> Children's Wordsymth:</td> <td> <input checked type="checkbox" id="choose_2" /> </td></tr>
                    <tr>
                        <td>Advanced Wordsymth: </td> <td><input type="checkbox" id="choose_3" checked=true /></td></tr>
                    <!-- <tr>
                        <td> Google Dict:</td> <td> <input type="checkbox" id="choose_4"  checked="true"/>
                        </td></tr> -->
                </table>

            </div>

            <ul id="renameList" class="contextMenu">
                <li class="edit">
                    <a href="#rename">Rename List</a>
                </li>

            </ul>
            <div id="dialog-form" title="Rename List" style="width:450px; display:none;background:lightgoldenrodyellow">
                <form>
                    <fieldset>
                        <label for="oldNameName"><b>Old List Name:</b></label>
                        <span id="oldListName"> </span> <br/> <br/>
                        <label for="newListName"><b>New list Name:</b></label> 
                        <input type="text" name="newListName" id="newListName" value="" class="text ui-widget-content ui-corner-all" />

                    </fieldset>
                </form>
            </div>
            <%-- nodisplayable--%>

    </body>
</html>

<%!
    static boolean isMobile(HttpServletRequest request, HttpSession session) {
        if (session.getAttribute("mobile") != null) {
            return (Boolean) session.getAttribute("mobile");
        }
        String ua = request.getHeader("User-Agent").toLowerCase();
        java.util.regex.Pattern p = java.util.regex.Pattern.compile(".*(iPhone|mobile|iPod|blackberry|DoCoMo|cldc|android|htc|lg|midp|mmp|mobile|nokia|opera mini|palm|pocket|psp|sgh|smartphone|symbian|treo mini|Playstation Portable|SonyEricsson|Samsung|MobileExplorer|PalmSource|Benq|Windows Phone|Windows Mobile|IEMobile|Windows CE|Nintendo Wii).*", java.util.regex.Pattern.CASE_INSENSITIVE);
        java.util.regex.Matcher matcher = p.matcher(ua);
        if (matcher.matches()) {
            session.setAttribute("mobile", true);
            return true;
        } else {
            session.setAttribute("mobile", false);
            return false;
        }
    }

    enum Browser {

        IE,
        Firefox,
        CHROME;
    };

    static Browser browser(HttpServletRequest request) {
        String ua = request.getHeader("User-Agent");

        if (ua != null && ua.indexOf("MSIE") != -1) {
            return Browser.IE;
        }

        if (ua != null && ua.indexOf("Chrome/") != -1) {
            return Browser.CHROME;
        }
        //boolean isSafari = (!isChrome && (ua != null && ua.indexOf("Safari/") != -1));

        if (ua != null && ua.indexOf("Firefox/") != -1) {
            return Browser.Firefox;
        }
        return null;

    }
%>
